package com.cfweb.controller.system;

import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpSession;
import javax.ws.rs.Consumes;
import javax.ws.rs.FormParam;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.cfweb.api.DomainApi;
import com.cfweb.controller.LoginHandler;
import com.cfweb.dao.AppTemplateMapper;
import com.cfweb.domain.AppTemplate;
import com.cfweb.domain.AppTemplateExample;
import com.cfweb.util.ExtJSResponse;

/**
 * 
 * @author dt
 *
 */
@Service
@Path("/domain")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public class DomainManagement {
	
	private Logger logger = Logger.getLogger(OrgManagement.class);
	
	@Autowired  
	private HttpSession session; 
	
	@Autowired
	private AppTemplateMapper apptemMapper;
	
	/**
     * list all of domain
     * @param orgName
     * @return list
     */
	@Path("/listall")
	@GET
	public ExtJSResponse listall(@QueryParam("orgName") String orgName) {
		List<Map<String, Object>> domains = null;
		try {
			//CloudFoundryClient client = (CloudFoundryClient) session.getAttribute(LoginHandler.CLIENT);
			if(orgName == null || "".equals(orgName)) {
				domains = DomainApi.get_domains_for_org(session, (String) session.getAttribute(LoginHandler.ORG));
			} else {
				domains = DomainApi.get_domains_for_org(session, orgName);
			}
		} catch(Exception e) {
			logger.error(e);
			return ExtJSResponse.errorRes();
		}
		if (domains != null) {
		    return ExtJSResponse.successResWithData(domains);
		}
		return ExtJSResponse.errorRes();
	}
	
	/**
     * list domains of an org
     * @param orgName
     * @return list<domain>
     */
	@Path("/list")
	@GET
	public ExtJSResponse list(@QueryParam("orgName") String orgName) {
		List<Map<String, Object>> domains = null;
		try {
			//CloudFoundryClient client = (CloudFoundryClient) session.getAttribute(LoginHandler.CLIENT);
			domains = DomainApi.get_domains_for_org(session, orgName);
		} catch(Exception e) {
			logger.error(e);
			return ExtJSResponse.errorRes();
		}
		if (domains != null) {
		    return ExtJSResponse.successResWithData(domains);
		}
		return ExtJSResponse.errorRes();
	}
	
	/**
     * add a shared-domain
     * @param domainName
     * @return success or error
     */
	@Path("/add-shared")
	@POST
	@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
	public ExtJSResponse addShared(@FormParam("domainName") String domainName) throws Exception {
		if (!DomainApi.create_shared_domain(session, domainName)) {
		    return ExtJSResponse.errorRes();
		}
		return ExtJSResponse.successRes();
	}
	
	/**
     * delete a shared-domain
     * @param domainName
     * @return success or error
     */
	@Path("/delete-shared")
	@GET
	public ExtJSResponse deleteShared(@QueryParam("domainName") String domainName) throws Exception {
		if (DomainApi.delete_shared_domain(session, domainName)) {
			AppTemplateExample apptemEx = new AppTemplateExample();
			apptemEx.createCriteria().andDomainEqualTo(domainName);
			List<AppTemplate> atemlist = apptemMapper.selectByExample(apptemEx);
			if(atemlist.size() != 0) {
				for(AppTemplate atem:atemlist) {
					atem.setDomain("");
					apptemMapper.updateByPrimaryKey(atem);
				}
			}
			return ExtJSResponse.successRes();
		}
		return ExtJSResponse.errorRes();
		
	}
	
	/**
     * add a private-domain
     * @param domainName
     * @return success or error
     */
	@Path("/add-private")
	@POST
	@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
	public ExtJSResponse addPrivate(@FormParam("orgName") String orgName, 
			@FormParam("domainName") String domainName) throws Exception {
		if (!DomainApi.create_private_domain_for_org(session, orgName, domainName)) {
		    return ExtJSResponse.errorRes();
		}
		return ExtJSResponse.successRes();
	}
	
	/**
     * delete a private-domain
     * @param domainName
     * @param orgName
     * @return success or error
     */
	@Path("/delete-private")
	@GET
	public ExtJSResponse deletePrivate(@QueryParam("orgName") String orgName,
			@QueryParam("domainName") String domainName) throws Exception {
		if (DomainApi.delete_private_domain_for_org(session, orgName, domainName)) {
			AppTemplateExample apptemEx = new AppTemplateExample();
			apptemEx.createCriteria().andDomainEqualTo(domainName).andOrgEqualTo(orgName);
			List<AppTemplate> atemlist = apptemMapper.selectByExample(apptemEx);
			if(atemlist.size() != 0) {
				for(AppTemplate atem:atemlist) {
					atem.setDomain("");
					apptemMapper.updateByPrimaryKey(atem);
				}
			}
			return ExtJSResponse.successRes();
		}
		return ExtJSResponse.errorRes();
		
	}
	
	/**
     * remove a domain
     * @param domainName
     * @return success or error
     */
	@Path("/remove")
	@GET
	public ExtJSResponse remove(@QueryParam("domainName") String domainName,
			@QueryParam("orgName") String orgName) throws Exception { 
		if(!DomainApi.remove_domain(session, orgName, domainName)) {
		    return ExtJSResponse.errorRes();
		}
		return ExtJSResponse.successRes();
	}
	
	/**
     * check a domainName
     * @param domainName
     * @param isShared
     * @return success or error
     */
	@Path("/checkDomainName")
	@GET
	public ExtJSResponse checkDomainName(@QueryParam("domainName") String domainName, @QueryParam("isShared") boolean isShared) throws Exception {
		try {
			if(DomainApi.isShareDomainExist(session, domainName)) {
					return ExtJSResponse.successResWithData(false);
			}
			if(DomainApi.isPrivateDomainExist(session, domainName)) {
					return ExtJSResponse.successResWithData(false);
			}
		} catch(Exception e) {
			throw e;
		}
		return ExtJSResponse.successResWithData(true);
	}

}
